<template>
  <div class="container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-row>
          <el-col :span="6">
            <el-form-item label="楼栋">
              <el-input
                v-model="searchForm.building"
                placeholder="请输入楼栋"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="教室编号">
              <el-input
                v-model="searchForm.classNumber"
                placeholder="请输入教室编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleResetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 列表 -->
    <div class="common-layout-main">
      <div class="common-head">
        <el-button type="primary" @click="handleAdd">添加教室</el-button>
      </div>
      <el-table :data="rooms" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column
          prop="building"
          label="楼栋"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="classNumber"
          label="教室编号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="capacity"
          label="容纳人数"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="gmtCreate"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="gmtModified"
          label="修改时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:currentPage="pagination.pageNum"
        v-model:pageSize="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 50, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchRooms"
        @current-change="fetchRooms"
      />
    </div>

    <!-- 编辑/添加弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="roomForm" :model="roomData" :rules="rules">
        <el-form-item
          label="楼栋"
          :label-width="formLabelWidth"
          prop="building"
        >
          <el-input v-model="roomData.building" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="教室编号"
          :label-width="formLabelWidth"
          prop="classNumber"
        >
          <el-input v-model="roomData.classNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="容纳人数"
          :label-width="formLabelWidth"
          prop="capacity"
        >
          <el-input v-model="roomData.capacity" type="number"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted } from "vue";
import { FormInstance } from "element-plus";
import {
  getRoomList,
  getRoomById,
  deleteRoom,
  addRoom,
  updateRoom,
} from "@/api/classroom";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  setup() {
    const rooms = ref<any[]>([]);
    const roomData = reactive({
      id: "",
      roomName: "",
      classNumber: "",
      capacity: "",
    });
    const searchForm = reactive({
      roomName: null,
      classNumber: null,
    });
    const pagination = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });
    const dialogVisible = ref(false);
    const dialogTitle = ref("");
    const formLabelWidth = "120px";

    const rules = reactive({
      building: [{ required: true, message: "楼栋不能为空", trigger: "blur" }],
      classNumber: [
        { required: true, message: "教室编号不能为空", trigger: "blur" },
      ],
      capacity: [
        { required: true, message: "容纳人数不能为空", trigger: "blur" },
      ],
    });

    const roomForm = ref<FormInstance | null>(null);

    const fetchRooms = async () => {
      try {
        const response = await getRoomList({
          ...searchForm,
          ...pagination,
        });
        rooms.value = response.data;
        pagination.total = response.total;
      } catch (error) {
        console.error("Error fetching rooms:", error);
      }
    };

    const handleAdd = () => {
      Object.assign(roomData, {
        id: "",
        building: "",
        classNumber: "",
        capacity: "",
      });
      dialogTitle.value = "添加教室";
      dialogVisible.value = true;
    };

    const handleEdit = async (row: any) => {
      const {data} = await getRoomById(row.id);
      Object.assign(roomData, data);
      dialogTitle.value = "编辑教室";
      dialogVisible.value = true;
    };

    const handleDelete = async (id: string) => {
      try {
        ElMessageBox.confirm("是否删除该教室？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          await deleteRoom(id);
          fetchRooms();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        });
      } catch (error) {
        console.error("Error deleting room:", error);
      }
    };

    const handleSubmit = () => {
      roomForm.value?.validate(async (valid) => {
        if (valid) {
          if (roomData.id) {
            try {
              await updateRoom(roomData);
              fetchRooms();
              ElMessage({
                type: "success",
                message: "修改成功",
              });
            } catch (error) {
              console.error("Error updating room:", error);
            }
          } else {
            try {
              await addRoom(roomData);
              fetchRooms();
              ElMessage({
                type: "success",
                message: "添加成功",
              });
            } catch (error) {
              console.error("Error creating room:", error);
            }
          }
          dialogVisible.value = false;
        } else {
          console.log("表单验证失败");
        }
      });
    };

    const handleSearch = () => {
      pagination.pageNum = 1;
      fetchRooms();
    };

    const handleResetSearch = () => {
      Object.assign(searchForm, { roomName: null, classNumber: null });
      handleSearch();
    };

    onMounted(() => {
      fetchRooms();
    });

    return {
      rooms,
      roomData,
      searchForm,
      dialogVisible,
      dialogTitle,
      pagination,
      formLabelWidth,
      rules,
      roomForm,
      fetchRooms,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleSearch,
      handleResetSearch,
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  .search-form {
    background: #fff;
    padding: 15px 10px 0;
    margin-bottom: 10px;
  }
  .common-layout-main {
    background-color: #fff;
    padding: 15px 10px 0;
  }
}
</style>
